package com.com.datastructures.search;

import java.util.Arrays;

/**
 * Created by User on 21/08/2015.
 */
public class BinarySearch
{
    int arr[];
    int item;
    BinarySearch(int a[], int item)
    {
        this.arr = a;
        this.item = item;
        Arrays.sort(arr);
    }

    public int search()
    {
        int beg = 0;
        int end = arr.length-1;

        while (beg <= end)
        {
            int mid = (beg + end)/2;
            if(arr[mid] == item)
            {
                return mid;
            }
            else if(arr[mid]> item)
            {
                end = mid-1;
            }
            else
            {
                beg = mid+1;
            }
        }
        return -1;
    }

    public static void main(String[] args)
    {
        //System.out.println((1+0)/2);

        int a[] = {2,6,2,3,2,12,23,45,-1};

        int item = 45;
        BinarySearch algo = new BinarySearch(a,item);
        int location = algo.search();
        if(location >= 0)
        {
            System.out.println("Item found at location : "+ location);
        }
        else
        {
            System.out.println("Item could not be found!");
        }
    }
}
